<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form :model="userInfo" label-width="90px" :rules="userInfoRules" ref="userInfoRef">
      <el-form-item label="登录名称">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户名称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交修改</el-button>
        <el-button @click="recet">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user.js'
export default {
  name: 'userinfo',
  data() {
    return {
      userInfo: {
        ...this.$store.state.user.user
        // 或者 userinfo=Object.assign({},this.$store.state.user.user)
      },
      // 定义一个验证规则对象
      userInfoRules: {
        nickname: [
          { required: true, message: '昵称为1-10位非空字符串', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称为1-10位非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱为必填项', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    recet() {
      this.$refs.userInfoRef.resetFields()
      // 重新进行浅拷贝更新重置的数据
      this.userInfo = Object.assign({}, this.$store.state.user.user)
    },
    update() {
      this.$refs.userInfoRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updateUserAPI(this.userInfo)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$store.dispatch('user/initUser')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
